package com.xusheng.cli.core.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.xusheng.cli.entity.backAgentModule.BackAgent;
import com.xusheng.cli.entity.rechargeModule.Recharge;
import com.xusheng.cli.mapper.FrontUserMapper;
import com.xusheng.cli.service.BackAgentService;
import com.xusheng.cli.service.RechargeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 王鹤然
 * @since 2020-10-25 01:47
 */
@Component
@Slf4j
public class WithdrawTask {


    @Resource
    private FrontUserMapper frontUserMapper;
    @Resource
    private RechargeService rechargeService;
    @Resource
    private BackAgentService backAgentService;


    /**
     * 每天更新签到状态
     *
     * @author 王鹤然
     * @date 2022/11/25 0025 下午 17:27
     */
    @Async("taskExecutor")
    @Scheduled(cron = "5 0 0 * * ?")
    public void updateTodaySign() {
        // 获取前一天日期
        DateTime dateTime = DateUtil.offsetDay(new Date(), -1);
        DateTime endDate = DateUtil.endOfDay(dateTime);
        List<Recharge> rechargeList = rechargeService.lambdaQuery().eq(Recharge::getWithdraw, false).le(Recharge::getPayTime, endDate).list();
        for (Recharge recharge : rechargeList) {
            List<BackAgent> backAgents = new ArrayList<>();
            if (recharge.getProxyOneId() != null) {
                BackAgent backAgentLevel1 = backAgentService.getById(recharge.getProxyOneId());
                backAgentLevel1.setBalance(backAgentLevel1.getBalance().add(recharge.getProxyOneIncome()));
                backAgents.add(backAgentLevel1);
            }
            if (recharge.getProxyTwoId() != null) {
                BackAgent backAgentLevel2 = backAgentService.getById(recharge.getProxyTwoId());
                backAgentLevel2.setBalance(backAgentLevel2.getBalance().add(recharge.getProxyTwoIncome()));
                backAgents.add(backAgentLevel2);
            }
            if (recharge.getProxyThreeId() != null) {
                BackAgent backAgentLevel3 = backAgentService.getById(recharge.getProxyThreeId());
                backAgentLevel3.setBalance(backAgentLevel3.getBalance().add(recharge.getProxyThreeIncome()));
                backAgents.add(backAgentLevel3);
            }
            log.info("当前订单{}中，各个代理的余额变化{}", recharge.getId(), backAgents);
            backAgentService.updateBatchById(backAgents);
            recharge.setWithdraw(true);
        }
        // 批量更新订单结算状态
        rechargeService.updateBatchById(rechargeList);
        log.info("执行定时任务:updateTodaySign");
    }

}
